﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Linq
{
    /// <summary>
    /// IEnumerable扩展
    /// </summary>
    public static class IEnumerableExtension
    {
        /// <summary>
        /// 是否不为空且包含数据
        /// </summary>
        /// <typeparam name="TSource">集合类型</typeparam>
        /// <param name="lists"></param>
        /// <returns></returns>
        public static bool IsNotNullAndAny<TSource>(this IEnumerable<TSource> lists)
        {
            return lists.IsNotNull() && lists.Any();
        }

        /// <summary>
        /// 集合合并为字符串
        /// </summary>
        /// <param name="lists"></param>
        /// <param name="separator">分隔符</param>
        /// <returns></returns>
        public static string Join(this IEnumerable<string> lists, string separator = ",")
        {
            if (lists.IsNull()) return string.Empty;

            return string.Join(separator, lists.ToArray());
        }

        /// <summary>
        /// 循环遍历
        /// </summary>
        /// <typeparam name="TSource">集合类型</typeparam>
        /// <param name="lists"></param>
        /// <param name="func">循环回调函数</param>
        public static void ForEach<TSource>(this IEnumerable<TSource> lists, Action<TSource> func)
        {
            if (func.IsNull()) return;

            foreach (var item in lists)
            {
                func(item);
            }
        }

        /// <summary>
        /// 平均值可空
        /// </summary>
        /// <param name="objs"></param>
        /// <returns></returns>
        public static decimal AverageCanNull(this IEnumerable<decimal> objs)
        {
            if (!objs.IsNotNullAndAny()) return 0m;

            return objs.Sum() / objs.Count();
        }
    }
}
